package com.example.memorypoint.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import com.example.memorypoint.DateBase.DiaryDatabase;
import com.example.memorypoint.R;
import com.example.memorypoint.activity.MainActivity;
import com.example.memorypoint.activity.WriteActivity;
import com.example.memorypoint.adapter.FragmentAdapter;
import com.example.memorypoint.entity.Diary;

import java.util.Objects;


public class DiaryFragment extends Fragment implements View.OnClickListener {

    private ImageView weather;
    private ImageView emoji;
    private ImageView fg_menu;
    private TextView date;
    private TextView title;
    private RelativeLayout diary_fragment;
    private RelativeLayout rl_fragment;
    private PopupMenu popupMenu;
    private Diary diary;
    private int[] weathers = {R.drawable.ic_wether_bigheavilyrain, R.drawable.ic_wether_bigrain, R.drawable.ic_wether_bigsnow, R.drawable.ic_wether_cloudy, R.drawable.ic_wether_cold, R.drawable.ic_wether_dayrain, R.drawable.ic_wether_floatdust, R.drawable.ic_wether_foggy, R.drawable.ic_wether_freezingrain, R.drawable.ic_wether_heavilyrain, R.drawable.ic_wether_heavilysnow, R.drawable.ic_wether_lightrain, R.drawable.ic_wether_lightsnow, R.drawable.ic_wether_midrain, R.drawable.ic_wether_midsnow, R.drawable.ic_wether_nightcloudy, R.drawable.ic_wether_nightfoggy, R.drawable.ic_wether_nightrain, R.drawable.ic_wether_nightsnow, R.drawable.ic_wether_nightsun, R.drawable.ic_wether_rainsnow, R.drawable.ic_wether_sandblow, R.drawable.ic_wether_sandstorm, R.drawable.ic_wether_suddenrainsnow, R.drawable.ic_wether_suncloudy, R.drawable.ic_wether_sunfoggy, R.drawable.ic_wether_sunny, R.drawable.ic_wether_sunsnow, R.drawable.ic_wether_thunderrain, R.drawable.ic_wether_typhoon};
    private int[] emojis = {R.drawable.ic_emoji_alien, R.drawable.ic_emoji_anger, R.drawable.ic_emoji_big_cry, R.drawable.ic_emoji_cry, R.drawable.ic_emoji_ghost, R.drawable.ic_emoji_giggle, R.drawable.ic_emoji_happy, R.drawable.ic_emoji_hurt, R.drawable.ic_emoji_joker, R.drawable.ic_emoji_laugh, R.drawable.ic_emoji_love, R.drawable.ic_emoji_null, R.drawable.ic_emoji_rhinorrhea, R.drawable.ic_emoji_sb, R.drawable.ic_emoji_scorn, R.drawable.ic_emoji_shit, R.drawable.ic_emoji_sleep, R.drawable.ic_emoji_small_love, R.drawable.ic_emoji_smile, R.drawable.ic_emoji_soclerver, R.drawable.ic_emoji_speechless, R.drawable.ic_emoji_star, R.drawable.ic_emoji_study, R.drawable.ic_emoji_vomit, R.drawable.ic_emoji_what};
    private static int[] backgrounds = {R.drawable.ic_backgroud_first, R.drawable.ic_background_second, R.drawable.ic_background_third, R.drawable.ic_background_forth, R.drawable.ic_background_fifth, R.drawable.ic_background_sixth, R.drawable.ic_background_seventh, R.drawable.ic_background_eight, R.drawable.ic_background_nine};

    public DiaryFragment(Diary mDiary) {
        diary = mDiary;
     }

    public static DiaryFragment getInstance(Diary mDiary) {
        DiaryFragment shopCardFragment = new DiaryFragment(mDiary);
        return shopCardFragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @SuppressLint({"CutPasteId", "RestrictedApi", "MissingInflatedId", "NonConstantResourceId"})
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_diary, container, false);
        //初始化视图
        weather = view.findViewById(R.id.weather);
        emoji = view.findViewById(R.id.emoji);
        fg_menu = view.findViewById(R.id.fg_menu);
        date = view.findViewById(R.id.date);
        title = view.findViewById(R.id.tv_title);
        diary_fragment = view.findViewById(R.id.diary_fragment);
        rl_fragment = view.findViewById(R.id.rl_fragment);
        initView();
        //设置监听
        diary_fragment.setOnClickListener(this);
        weather.setOnClickListener(this);
        emoji.setOnClickListener(this);
        fg_menu.setOnClickListener(this);
        initText();
        // 定义PopupMenu，并设置样式
        initPopupMenu();
        return view;
    }

    private void initView() {
        rl_fragment.setBackground(getContext().getDrawable(backgrounds[diary.getId() % backgrounds.length]));
    }

    @SuppressLint("SuspiciousIndentation")
    private void initText() {
        String low = "-1";
        if (diary != null) {
            if (diary.getTitle() != null)
                title.setText(diary.getTitle());
            date.setText(diary.getDate());
            if (!low.equals(String.valueOf(diary.getWeather()))) {
                weather.setImageDrawable(getContext().getDrawable(weathers[diary.getWeather()]));
            }
            if (!low.equals(String.valueOf(diary.getEmoji()))) {
                emoji.setImageDrawable(getContext().getDrawable(emojis[diary.getEmoji()]));
            }
        }
    }

    private void initPopupMenu() {
        popupMenu = new PopupMenu(getContext(), fg_menu);
        popupMenu.getMenuInflater().inflate(R.menu.menu, popupMenu.getMenu());
        popupMenu.setForceShowIcon(true);
        popupMenu.setOnMenuItemClickListener(item -> {
            if (item.getItemId() == R.id.delete) {// 执行删除操作
                deleteDiary();
                return true;
            }
            return false;
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.weather) {
        } else if (id == R.id.fg_menu) {
            popupMenu.show();
        } else if (id == R.id.diary_fragment) {
            onWriteDiaryClick();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshDiary();
    }

    private void deleteDiary() {
        // 创建一个AlertDialog.Builder对象
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setMessage("您确定要删除吗？")
                .setPositiveButton("确定", (dialog, id) -> {
                    // 调用DiaryDatabase的deleteDiary方法删除日记
                    DiaryDatabase database = new DiaryDatabase(requireContext());
                    database.deleteDiary(diary.getId());

                    // 在ViewPager中删除当前Fragment
                    FragmentManager fragmentManager = getParentFragmentManager();
                    FragmentTransaction transaction = fragmentManager.beginTransaction();
                    transaction.remove(DiaryFragment.this);
                    transaction.commit();
                    // 从适配器中删除当前的DiaryFragment并更新ViewPager的当前显示页面
                    FragmentAdapter adapter = MainActivity.getInstance().getDiaryPagerAdapter();
                    ViewPager viewPager = MainActivity.getInstance().getViewPager();
                    int currentItem = viewPager.getCurrentItem();
                    adapter.removeFragment(currentItem);
                    Toast.makeText(this.requireContext(), "成功删除", Toast.LENGTH_SHORT).show();

                    // 更新ViewPager的当前显示页面
                    if (currentItem > 0) {
                        viewPager.setCurrentItem(currentItem - 1);
                    } else if (adapter.getCount() > 0) {
                        viewPager.setCurrentItem(0);
                    }
                    // 重新加载ViewPager显示所有的Fragment
                    MainActivity.getInstance().initAdapter();

                })
                .setNegativeButton("取消", (dialog, id) -> {
                    // 用户点击取消按钮，不执行任何操作
                });

        // 创建并显示弹窗
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    public void onWriteDiaryClick() {
        // 创建一个Bundle对象，将日记的id作为参数传递给写日记界面
        Bundle args = new Bundle();
        args.putInt(WriteActivity.EXTRA_DIARY_ID, diary.getId());
        args.putString(WriteActivity.EXTRA_DIARY_DATE, diary.getDate());
        // 创建 Intent 对象，并将 Bundle 设置为其 extras 属性
        Intent intent = new Intent(getContext(), WriteActivity.class);
        intent.putExtras(args);
        // 启动 WriteActivity
        startActivity(intent);
    }

    //更新表情和天气，从数据库中获取
    private void refreshDiary() {
        DiaryDatabase database = new DiaryDatabase(requireContext());
        diary = database.getDiaryById(diary.getId()); // 重新获取日记
        initText(); // 重新加载 UI
    }

}